package com.zxy.demo.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags={"系统控制中心"})
@Controller
public class SysController {
	private static final String CRON_PAGE = "cron";
	private static final String LOGIN_PAGE = "login";
	
	@ApiOperation(value="自动跳转到主页", httpMethod = "GET")
	@GetMapping("/")
	public String home(Model model, HttpServletRequest request) {
		return "redirect:/task/home";
	}
	
	@ApiOperation(value="跳转cron表达式生成页", httpMethod = "GET")
	@GetMapping("/showCron")
	public String showCron() {
		return CRON_PAGE;
	}
	
	// 跳登录页面
	@ApiOperation(value="跳登录页面", httpMethod = "GET")
	@GetMapping("/login")
	public String login(HttpServletRequest request) {
		Object object = request.getSession().getAttribute("login_user");
		// 已在线的不能访问登录页面
		if(null == object) {
			return LOGIN_PAGE;
		} else {
			return "redirect:/task/home";
		}
	}
	
	// 登录
	@ApiOperation(value="登录", httpMethod = "POST")
	@PostMapping("/toLogin")
	public String toLogin(String account, String password,HttpServletRequest request,Model model) {
		if("zeng1994".equals(account) && "zeng1994".equals(password)) {
			request.getSession().setAttribute("login_user", account);
			// 耍了个小心机 ，url链接到我的博客
			request.getSession().setAttribute("login_user_blog", "http://www.cnblogs.com/zeng1994/");
			return "redirect:/task/home";
		} else {
			if(StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
				model.addAttribute("msg", "账号或密码不能为空");
			} else {
				model.addAttribute("msg", "账号或密码错误");
			}
			// 返回登录页面给浏览器
			return LOGIN_PAGE;
		}
	}
	
	// 退出登录
	@ApiOperation(value="退出登录", httpMethod = "GET")
	@GetMapping("/logout")
	public String logout(HttpServletRequest request) {
		// 清空session
		request.getSession().invalidate();
		// 重定向到登录页面
		return "redirect:/login";
	}
}
